import 'package:flutter/material.dart';
import '../../common/ScreenAdaper.dart';
import 'package:dio/dio.dart';
import '../../config/Config.dart';
import '../../widget/LoadingWidget.dart';
import '../../widget/Tool.dart';
import '../../services/Storage.dart';

class BookPage extends StatefulWidget {
  Map arguments;
  BookPage({Key key,this.arguments}) : super(key: key);
  _BookPageState createState() => _BookPageState();
}

class _BookPageState extends State<BookPage> {
  ScrollController _controller = new ScrollController();
  Map _data = {};
  List _chapterData = [];
  List _newChapterData = [];
  String _status = "未知";
  String _token = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getDate();
    _getChapter();
    _getToken();
  }
  @override
  void dispose() {
    //为了避免内存泄露，需要调用_controller.dispose
    _controller.dispose();
    super.dispose();
  }

  // 获取书籍信息
  _getDate() async{
    var apiUrl = "${Config.domain}api/book/show?bookid=${widget.arguments["bookId"]}";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    var status = "未知";
    if(list['code'] == 1){
      if (list["data"]["Status"] == 1){
        status = "完结";
      } else if(list["data"]["Status"] == 2){
        status = "连载中";
      }
      setState(() {
        this._data = list["data"];
        this._status = status;
      });
    }
  }
  // 获取章节信息
  _getChapter() async{
    var apiUrl = "${Config.domain}api/book/chapter?bookid=${widget.arguments["bookId"]}";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(_chapterData.length >= 5){
      setState(() {
        this._newChapterData = _chapterData.skip(_chapterData.length - 5).toList();
      });
    }
    if(list['code'] == 1){
      setState(() {
        this._chapterData = list["data"];
        if(_chapterData.length >= 5){
          this._newChapterData = _chapterData.skip(_chapterData.length - 5).toList();
        }
      });
    }
  }
  _getToken() async{
    try{
      String token = await Storage.getString("token");
      setState(() {
        this._token=token;
      });
    } catch (e){
      print(e);
    }
  }
  // 加入书签
  _addBookCase(int BookId,int ArticleId,String EndArticleName) async{
    var apiUrl = "${Config.domain}api/book/bookmark_add?token=${_token}";
    Response result=await Dio().post(apiUrl,data: {
      "BookId":BookId,
      "ArticleId":ArticleId,
      "EndArticleName":EndArticleName,
    });
    var list=result.data;
    Tool.ShowToast(list["msg"]);
  }

  @override
  Widget build(BuildContext context) {
    S.init(context);
    return Scaffold(
        appBar: AppBar(
          title: Text("《${_data["Name"]}》"),
          leading: GestureDetector(
            child: Icon(Icons.arrow_back,color: Colors.black54),
            onTap: (){
              Navigator.pop(context);
            },
          ),
          actions: <Widget>[
            Container(
              padding: EdgeInsets.only(right: 10),
              child: GestureDetector(
                child: Icon(Icons.home,color: Colors.black54),
                onTap: (){
                  Navigator.pushNamed(context, "/index");
                },
              ),
            )
          ],
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.arrow_upward),
          mini:true,
          onPressed: () {
            _controller.animateTo(.0,
                duration: Duration(milliseconds: 200),
                curve: Curves.ease
            );
          },
        ),
        body: Scrollbar(
          child: SingleChildScrollView(
            controller: _controller,
            child: Column(
              children: <Widget>[
                _data.length > 0 ? _info() : LoadingWidget(),
                _anniu(),
                SizedBox(height: 10,),
                _title("小说简介"),
                SizedBox(height: 10,),
                _description(),
                SizedBox(height: 10,),
                _title("最新章节"),
                SizedBox(height: 10,),
                _newChapterData.length > 0 ? _newContent() : LoadingWidget(),
                SizedBox(height: 10,),
                _title("正文"),
                SizedBox(height: 10,),
                _chapterData.length > 0 ? _chapterList() : LoadingWidget(),
              ],
            ),
          ),
        )
    );
  }

  Widget _info (){
    var _width = S.getScreenWidth() - S.width(260) - S.width(16) - S.width(18);
    return Container(
      padding: EdgeInsets.all(S.width(26)),
      child: Row(
        crossAxisAlignment:CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(S.width(8)),
            width: S.width(200),
            height: S.width(260),
//            child: Image.network("${_data["Image"]}",fit: BoxFit.cover,),
            child: FadeInImage.assetNetwork(image:"${_data["Image"]}",fit: BoxFit.cover,placeholder:"images/loading-1.gif"),
            decoration: BoxDecoration(
                border: Border.all(color: Colors.black54,width: 1)///边框颜色、宽
            ),
          ),
          Container(
            height: S.width(260),
            width: _width,
            padding: EdgeInsets.only(left: S.width(18)),
            child: Column(
              crossAxisAlignment:CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("${_data["Name"]}", maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: S.size(30),
                      fontWeight: FontWeight.bold),
                ),
                Container(
                  padding: EdgeInsets.only(top: 1, bottom: 1),
                  child: Text("作者：${_data["Author"]}", maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: S.size(28),
                          color: Colors.black54)
                  ),
                ),
                Row(
                  children: <Widget>[
                    Text("分类：", style: TextStyle(fontSize: S.size(28),color: Colors.black54)),
                    Text("${_data["Typename"]}", style: TextStyle(fontWeight: FontWeight.bold),)
                  ],
                ),
                Text("状态：${_status}",style: TextStyle(color: Colors.black54),maxLines: 1,overflow: TextOverflow.ellipsis,),
                Text("更新：${_data["Updatatime"]}",style: TextStyle(color: Colors.black54),maxLines: 1,overflow: TextOverflow.ellipsis,),
                Row(
                  children: <Widget>[
                    Text("最新：", style: TextStyle(fontSize: S.size(28),color: Colors.black54)),
                    Expanded(
                        child: GestureDetector(
                          child: Text(
                              "${_data["Endcase"]}",
                              style: TextStyle(fontWeight: FontWeight.bold,color: Colors.red),maxLines: 1,overflow: TextOverflow.ellipsis
                          ),
                          onTap: (){
                            Navigator.pushNamed(context, "/content",arguments: {
                              "articleId": _data['EndcaseId'],
                              "bookId": widget.arguments["bookId"]
                            });
                          },
                        ),
                    )
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
  Widget _anniu(){
    return _newChapterData.length > 0 ? Container(
      padding: EdgeInsets.only(left: S.width(20),right: S.width(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(
              child: RaisedButton(
                child: Text('开始阅读'),
                textColor: Colors.white,
                color: Colors.blue,
                onPressed: () {
                  Navigator.pushNamed(context, "/content",arguments: {
                    "articleId": _chapterData[0]["Id"],
                    "bookId": widget.arguments["bookId"]
                  });
                },
              )
          ),
          SizedBox(width: 20,),
          Expanded(
              child: RaisedButton(
                child: Text('加入书架'),
                textColor: Colors.white,
                color: Colors.blue,
                onPressed: () {
                  _addBookCase(widget.arguments["bookId"],_chapterData[0]["Id"]," --");
                },
              )
          ),
        ],
      ),
    ) : LoadingWidget();
  }
  Widget _title(String value){
    return Container(
      padding: EdgeInsets.only(left: S.width(10),right: S.width(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: S.width(10)),
            color: Color.fromARGB(255, 236, 240, 240),
            height: S.height(60),
            child: Row(
              children: <Widget>[
                Text("${value}")
              ],
            ),
          ),
          Divider(height: 0,thickness: S.height(4),color: Colors.blue,)
        ],
      ),
    );
  }
  Widget _description(){
    return Container(
      padding: EdgeInsets.only(left: S.width(10),right: S.width(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Text("${_data['Info']}",maxLines: 8,overflow: TextOverflow.ellipsis,),
          Row(
            children: <Widget>[
              Text("最新章节推荐地址：",style: TextStyle(color: Colors.black54),),
              Expanded(
                  child: GestureDetector(
                    child: Text("${_data['Endcase']}",maxLines: 1,overflow: TextOverflow.ellipsis,),
                    onTap: (){
                      Navigator.pushNamed(context, "/content",arguments: {
                        "articleId": _data['EndcaseId'],
                        "bookId": widget.arguments["bookId"]
                      });
                    },
                  ),
              )
            ],
          )
        ],
      ),
    );
  }
  Widget _newContent(){
    return Column(
      children: _newChapterData.map((v){
        return _rowTitle("${v["Name"]}","${v["Id"]}");
      }).toList(),
    );
  }
  Widget _chapterList(){
    return Column(
      children: _chapterData.map((v){
        return _rowTitle("${v["Name"]}","${v["Id"]}");
      }).toList(),
    );
  }

  // 章节
  Widget _rowTitle(String title,articleId){
    return Container(
      padding: EdgeInsets.only(left: S.width(10),right: S.width(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          GestureDetector(
            child: Text(title,maxLines: 1,overflow: TextOverflow.ellipsis,),
            onTap: (){
              Navigator.pushNamed(context, "/content",arguments: {
                "articleId": articleId,
                "bookId": widget.arguments["bookId"]
              });
            },
          ),
          Divider(),
        ],
      ),
    );
  }
}
